var Promise = require('bluebird');
var _ = require('underscore');
var Model = require('../models/menu');
var base = require('./baseService');
//标记删除
exports.Delete=function(req){
  return new Promise(function(resolve,reject){
    var delids = [];
    if(req.params.id)
        delids.push(req.param.id);
    else
				if(req.body.ids)
        delids = req.body.ids;
		Model.update({_id:{$in:delids}},{$set:{isdel:true}},{multi:true},function(err,tank){
			if (err) 
        return handleError(err);
			resolve(tank.nModified>0?base.Success("删除成功"):base.Error("删除失败"));
		});
  });
}
//保存菜单
exports.Save=async function(req){
  return new Promise(function(resolve, reject){
    var entity = req.body;

    if(!entity.menu||entity.menu===''){
      entity.menu=null;
    }

    var _entity = new Model(entity);
    _entity.save(function(err){
      if(err){
        reject(base.Error(err));
      }
      else
        //判断是否有父菜单
        if(_entity.menu){
          Model.findById(_entity.menu,function(err,parentModel){
            parentModel.menus.push(_entity.get('id'));
            parentModel.save(function(err){
              if(err)
                reject(base.Error(err));
              else
                resolve(base.Success("添加成功"))
            });
          });
        }
        resolve(base.Success("添加成功"))
    });

  });
  //保存菜单
}
exports.Update = async function(req){
  return new Promise(function(resolve, reject){
    var menu = req.body;
    Model.findById(menu._id,function(err,_menu){
      if(!menu.menu&&menu.menu!==_menu.menu){
        //修改老父菜单
        Model.findById(_menu.menu,function(err,parentModel){
          //将老菜单中的子菜单去掉 以防查询出错
          parentModel.menus.splice(parentModel.menus.indexOf(_menu._id),1);
          //保存老菜单
          parentModel.save(function(err){
            if(err)
              reject(base.Error(err));
          });
        });
        //修改新父菜单
        if(menu.menu){
          //找到新父菜单
          Model.findById(menu.menu,function(err,parentModel){
            //添加子菜单ID
            parentModel.menus.push(menu._id);
            //保存子菜单
            parentModel.save(function(err){
              if(err)
                reject(base.Error(err));
            });
          });
        }
      }

      var savedModel = _.extend(_menu,menu);
      if(!menu.menu){
        savedModel.menu=null;
      }
      savedModel.save(function(err){
        if(err)
          reject(base.Error(err));
        else
          resolve(base.Success("修改成功"));
      });
    });
  });
}
//获取一个
exports.Get=function(req){
  return new Promise(function(resolve,reject){
    var entityID = req.params.id;
    Model.findById(entityID,function(err,menu){
      if(err)
        reject(err);
      else
        resolve(menu);
    });
  });
}

//获取列表(分页)
exports.GetList=function(req){
  return new Promise(function(resolve, reject){
    var pe = base.GetPage(req);
    //添加条件
    var filter = {
      isdel:false
    };
    if(pe.getParam('title')){
      filter.title = new RegExp(pe.getParam('title')+'.*','i')
    }
    Model.find(filter)
    .limit(pe.getLimit())
    .skip(pe.getStartLine())
    .populate({
      path:'menu',
      select:'title',
      match:{isdel:false}
    })
    .exec(function(err,menus){
      if(err)
        reject(err);
      else{
        pe.data = menus;
        Model.count(filter).count(function(err,count){
          if(err)
            reject(err)
          else{
            pe.recordsFiltered = count;
            pe.recordsTotal = count;
            resolve(pe);
          }
        })
      }
    });
  });
}
/**
 * 扩展方法
 */

//获取顶级菜单
exports.GetRootList=function(req){
  return new Promise(function(resolve, reject){
    Model.find({menu:null,isdel:false},'_id title',function(err,menus){
      if(err)
        reject(err);
      else
        resolve(menus);
    });
  });
}
//获取所有菜单(暂时)
exports.GetAllList=function(req){
  return new Promise(function(resolve, reject){
    Model.find({menu:null,isdel:false})
    .populate({
      path: 'menus',
      select: 'title icon sort url',
      match:{ isdel: false },
      options:{ sort: { 'sort':-1} }
    })
    .exec(function(err,menus){
      if(err)
        reject(err);
      else{
        resolve(menus);
      }
    });
  });
}